<?php

namespace App\Repositories\RBAC;

use App\Models\RBAC\AdminUser;
use App\Repositories\BaseRepositoryEloquent;


/**
 * Class UserRepositoryEloquent.
 *
 * @package namespace App\Repositories;
 */
class UserRepositoryEloquent extends BaseRepositoryEloquent implements UserRepository
{

    /**
     * @var array
     */
    protected $fieldSearchable = [
        'username' => "like",
        'nickname' => "like",
        'email' => "like",
    ];

    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return AdminUser::class;
    }

    /**
     * 判断用户是否存在
     * @param $name
     * @param int $id
     * User: Zhangxy
     * Date: 2018-08-18
     * @return bool
     */
    public function existUser($name, $id = 0)
    {
        $userQuery = $this->model->where('username', $name);
        if (!empty($id)) {
            $userQuery = $userQuery->where('id', '<>', $id);
        }
        return $userQuery->count() ? true : false;
    }

    /**
     * 解绑某用户的角色
     * @param $userId
     * User: Zhangxy
     * Date: 2018-08-18
     */
    public function detachRoles($userId)
    {
        $this->model->find($userId)->roles()->detach();
    }

    /**
     * 给某用户绑定角色
     * @param $userId
     * @param $roleIds
     * User: Zhangxy
     * Date: 2018-08-18
     */
    public function assignRolesById($userId, $roleIds)
    {
        $roleRepository = app()->make(RoleRepository::class);
        $user = $this->model->find($userId);
        $roles = $roleRepository->findWhereIn('id', $roleIds);
        $user->assignRole($roles);
    }


}
